package com.peter.framework.service.memcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhCacheService implements CacheService {

	private CacheManager cacheManager;

	public EhCacheService() {
		cacheManager = new CacheManager(EhCacheService.class
				.getResource("ehcache.xml"));
		cacheManager.addCache(Cache.DEFAULT_CACHE_NAME);
	}

	@Override
	protected void finalize() throws Throwable {
		cacheManager.shutdown();
		super.finalize();
	}

	@Override
	public Object get(String key) {
		try {
			Cache cache = cacheManager.getCache(Cache.DEFAULT_CACHE_NAME);
			Element element = cache.get(key);
			if (element == null) {
				return null;
			}
			return element.getObjectValue();
		} catch (CacheException e) {
		}
		return null;
	}

	@Override
	public void put(String key, Object value) {
		try {
			Cache cache = cacheManager.getCache(Cache.DEFAULT_CACHE_NAME);
			Element element = new Element(key, value);
			cache.put(element);
		} catch (CacheException e) {
		}
	}

}
